package org.example.io;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/*
 *
 */
public class WriterTemplate {
    Logger log= LoggerFactory.getLogger(this.getClass());

    private final DataSource dataSource;
    private Connection connection;
    private final File dest;
    private final Charset charset;
    private RandomAccessFile randomAccessFile;
    public WriterTemplate(DataSource dataSource) throws SQLException
    {
        this.dataSource=dataSource;
        this.dest=null;
        this.charset=null;
        if(Objects.nonNull(this.dataSource)){
            log.debug("=========获取数据库连接==========");
            this.connection= dataSource.getConnection();
        }
    }
    public WriterTemplate(File dest, Charset charset) throws FileNotFoundException
    {
        this.dest=dest;
        this.charset=charset;
        this.dataSource=null;
        this.randomAccessFile=new RandomAccessFile(this.dest,"rw");
    }
    public void write(String message) throws IOException, SQLException
    {
        if(Objects.nonNull(this.connection))
        {
            ResultSet rs=connection.getMetaData().getTables(connection.getCatalog(), null,
                    "funny_message",null);
            if(!rs.next())
            {
                log.debug("=======创建funny_message表========");
                connection.createStatement().execute("creat table funny_message"+
                        "(id int primary key auto_increment, message_text text)");
                rs.close();
            }
            log.debug("======输出到数据表=======");
            connection.createStatement().executeUpdate("insert into "+
                    "funny_message values (null, '"+ message +"')");
        }else{
            log.debug("======输出到文件=====");
            randomAccessFile.seek(this.dest.length());
            randomAccessFile.write((message+"\n").getBytes(this.charset));
        }

    }
    public void close() throws SQLException, IOException
    {
        if(this.connection!=null){
            this.connection.close();
        }
        if(this.randomAccessFile!=null){
            this.randomAccessFile.close();
        }
    }
}
